<?php
class UserDirectory
{
  private $template_name;
  private $template_dir;
  private $path;
  
  public function prepare($user_dir,$template_dir,$template_name)
  {
  	$this->template_dir = $template_dir;
    $this->template_name = $template_name;
    $this->path = $user_dir;
    
	$this->refresh();
  }
  
  public function refresh()
  {
	$this->cleanUserDirectory();
	$this->copyTemplateData();      
  }
  
  
  private function cleanUserDirectory()
  {
    $user_dir = $this->path;
    $this->cleanUserDirectoryR($user_dir);
  }
  
  private function cleanUserDirectoryR($user_dir)
  {
    $dir = @opendir ($user_dir);
    
    while (($dir_entry = @readdir($dir)) !== false) 
    {
      if (($dir_entry != ".") && ($dir_entry != ".."))
      {
        if (is_file($user_dir."/".$dir_entry))
          unlink($user_dir."/".$dir_entry);
        else if (is_dir($user_dir."/".$dir_entry))
        {
            $this->cleanUserDirectoryR($user_dir."/".$dir_entry);
            rmdir($user_dir."/".$dir_entry);
        }
      }
    }
    @closedir ($dir);
    
  }
  
  private function copyTemplateData()
  {
  	$template_dir = $this->template_dir;
    $user_dir = $this->path;
    $this->copyTemplateDataR($template_dir,$user_dir);
  }
  
  private function copyTemplateDataR($template_dir,$user_dir)
  {
    $dir_listing = dir($template_dir);
    while(($dir_entry = $dir_listing->read()) !== false)
    {
      if (($dir_entry != ".") && ($dir_entry != ".."))
      {
        if (is_file($template_dir."/".$dir_entry))
          copy($template_dir."/".$dir_entry, $user_dir."/".$dir_entry);
        if (is_dir($template_dir."/".$dir_entry))
        {
          mkdir($user_dir."/".$dir_entry);
          $this->copyTemplateDataR($template_dir."/".$dir_entry,$user_dir."/".$dir_entry);
        } 
      }
    } 
  }
  
  
  public function getPath()
  {
    return $this->path;
  }
  
  public function getTemplateName()
  {
    return $this->template_name;
  }
}
?>